// ===================== TAB SWITCHING =====================
const tabs = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');

tabs.forEach(tab => {
  tab.addEventListener('click', () => {
    const target = tab.dataset.tab;

    // Hide all tabs
    tabContents.forEach(content => content.classList.add('hidden'));

    // Show selected tab
    document.getElementById(target + '-tab').classList.remove('hidden');

    // Active button style
    tabs.forEach(btn => btn.classList.remove('active'));
    tab.classList.add('active');

    // Load content
    if (target === 'calendar') loadCalendar();
    if (target === 'table') loadTable();
  });
});


// ===================== CALENDAR VIEW =====================
let calendarLoaded = false;
function loadCalendar() {
  if (calendarLoaded) return;

  fetch('../actions/fetch_meetings.php')
    .then(res => res.json())
    .then(events => {
      const calendarEl = document.getElementById('calendar');
      const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        height: 650,
        events: events.map(e => ({
          title: e.title,
          start: e.meeting_date,
          description: e.description,
        })),
        eventClick: info => {
          alert(`📅 ${info.event.title}\n${info.event.start.toDateString()}\n${info.event.extendedProps.description || ''}`);
        }
      });
      calendar.render();
      calendarLoaded = true;
    })
    .catch(err => console.error('Error loading calendar:', err));
}


// ===================== TABLE VIEW =====================
function loadTable() {
  fetch('../actions/fetch_meetings.php')
    .then(res => res.json())
    .then(data => {
      const tbody = document.getElementById('meetingsTable');
      tbody.innerHTML = '';
      data.forEach(row => {
        const tr = document.createElement('tr');
        tr.classList.add('hover:bg-gray-100');
        tr.innerHTML = `
          <td class="border px-3 py-2">${row.title}</td>
          <td class="border px-3 py-2">${row.meeting_date}</td>
          <td class="border px-3 py-2">${row.meeting_time}</td>
          <td class="border px-3 py-2">${row.venue}</td>
          <td class="border px-3 py-2">${row.organized_by}</td>
          <td class="border px-3 py-2">${row.contact_info}</td>
          <td class="border px-3 py-2">${row.status}</td>
        `;
        tbody.appendChild(tr);
      });
    })
    .catch(err => console.error('Error loading table:', err));
}


// ===================== ADD MEETING FORM =====================
document.getElementById('addMeetingForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const formData = new FormData(this);

  fetch('../actions/add_meeting.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.text())
  .then(response => {
    alert('✅ Meeting added successfully!');
    this.reset();

    // Reload data
    calendarLoaded = false;
    loadTable();
    loadCalendar();
  })
  .catch(err => console.error('Error adding meeting:', err));
});


// ===================== SUMMARY CARDS =====================
function loadSummary() {
  fetch('../actions/fetch_summary.php')
    .then(res => res.json())
    .then(data => {
      document.getElementById('totalMeetings').textContent = data.total || 0;
      document.getElementById('completedMeetings').textContent = data.completed || 0;
      document.getElementById('upcomingMeetings').textContent = data.upcoming || 0;
      document.getElementById('monthMeetings').textContent = data.this_month || 0;
    })
    .catch(err => console.error('Error loading summary:', err));
}


// ===================== INITIAL LOAD =====================
document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('[data-tab="calendar"]').click(); // Default tab
  loadSummary();
});
